// widgets/examine_task_cell.dart
import 'package:flutter/material.dart';
import 'package:oktoast/oktoast.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'package:sjx/repository/sjx_api.dart';

import '../examine_task_model.dart';

class ExamineTaskCell extends StatelessWidget {
  final ExamineTaskModel model;
  final ExamineTaskType type;
  final VoidCallback onReload;

  const ExamineTaskCell({
    Key? key,
    required this.model,
    required this.type,
    required this.onReload,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.all(10),
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(8),
        boxShadow: [
          BoxShadow(
            color: Colors.grey.withOpacity(0.2),
            blurRadius: 4,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildTopInfo(context),
          const SizedBox(height: 10),
          _buildComment(),
          if (model.submitImages.isNotEmpty) ...[
            const SizedBox(height: 10),
            _buildImages(),
          ],
          if (this.type == ExamineTaskType.daishenhe) ...[
            const SizedBox(height: 10),
            _buildActionButtons(context),
          ],
        ],
      ),
    );
  }

  Widget _buildTopInfo(BuildContext context) {
    return GestureDetector(
      onTap: () => _showUserActionSheet(context),
      child: RichText(
        text: TextSpan(
          children: [
            const TextSpan(
              text: '提交人：',
              style: TextStyle(color: Colors.grey, fontSize: 13),
            ),
            TextSpan(
              text: model.nickName,
              style: TextStyle(
                color: Theme.of(context).primaryColor,
                fontSize: 13,
              ),
            ),
            const TextSpan(
              text: '   提交时间：',
              style: TextStyle(color: Colors.grey, fontSize: 13),
            ),
            TextSpan(
              text: model.submitTime,
              style: const TextStyle(color: Colors.grey, fontSize: 13),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildComment() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(8),
      decoration: BoxDecoration(
        color: Colors.grey[50],
        borderRadius: BorderRadius.circular(4),
      ),
      child: SelectableText(
        model.comment,
        style: const TextStyle(fontSize: 15, height: 1.4),
      ),
    );
  }

  Widget _buildImages() {
    return SizedBox(
      height: 100,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: model.submitImages.length,
        itemBuilder: (context, index) {
          return GestureDetector(
            onTap: () => _showImagePreview(context, index),
            child: Container(
              width: 100,
              height: 100,
              margin: const EdgeInsets.only(right: 10),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(4),
                image: DecorationImage(
                  image: NetworkImage(model.submitImages[index]),
                  fit: BoxFit.cover,
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildActionButtons(BuildContext context) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        OutlinedButton(
          onPressed: () => _jujuePress(context),
          style: OutlinedButton.styleFrom(
            foregroundColor: Colors.grey,
            side: const BorderSide(color: Colors.grey),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(14),
            ),
          ),
          child: const Text('拒绝'),
        ),
        const SizedBox(width: 20),
        OutlinedButton(
          onPressed: () => _tongguoPress(context),
          style: OutlinedButton.styleFrom(
            foregroundColor: Theme.of(context).primaryColor,
            side: BorderSide(color: Theme.of(context).primaryColor),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(14),
            ),
          ),
          child: const Text('通过'),
        ),
      ],
    );
  }

  void _showUserActionSheet(BuildContext context) {
    showModalBottomSheet(
      context: context,
      builder: (context) => SafeArea(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.block),
              title: const Text('加入黑名单'),
              onTap: () {
                Navigator.of(context).pop();
                _addToBlacklist(context);
              },
            ),
            ListTile(
              leading: const Icon(Icons.cancel),
              title: const Text('取消'),
              onTap: () => Navigator.of(context).pop(),
            ),
          ],
        ),
      ),
    );
  }

  void _addToBlacklist(BuildContext context) async {
    // 加入黑名单逻辑
    await SJXApi.instance().setBlackList(this.model.platformId);
    showToast('已加入黑名单');
  }

  void _tongguoPress(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('通过任务'),
        content: const Text('通过后，奖赏将自动转到对方账户内。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop();
              _executeTongguo();
            },
            child: const Text('通过'),
          ),
        ],
      ),
    );
  }

  void _jujuePress(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => _RejectDialog(
        onConfirm: (reason) => _executeJujue(reason),
      ),
    );
  }

  void _executeTongguo() async {
    // 执行通过逻辑
    await SJXApi.instance().taskManagementPass(this.model.orderNo);
    this.onReload();
  }

  void _executeJujue(String reason) async {
    // 执行拒绝逻辑
    await SJXApi.instance().taskManagementReject(this.model.orderNo, reason);
    this.onReload();
  }

  void _showImagePreview(BuildContext context, int initialIndex) {
    showDialog(
      context: context,
      builder: (context) => Dialog(
        child: PhotoViewGallery.builder(
          itemCount: model.submitImages.length,
          builder: (context, index) {
            return PhotoViewGalleryPageOptions(
              imageProvider: NetworkImage(model.submitImages[index]),
              minScale: PhotoViewComputedScale.contained,
              maxScale: PhotoViewComputedScale.covered * 2,
            );
          },
          backgroundDecoration: const BoxDecoration(
            color: Colors.black,
          ),
          pageController: PageController(initialPage: initialIndex),
        ),
      ),
    );
  }
}

class _RejectDialog extends StatefulWidget {
  final Function(String) onConfirm;

  const _RejectDialog({Key? key, required this.onConfirm}) : super(key: key);

  @override
  __RejectDialogState createState() => __RejectDialogState();
}

class __RejectDialogState extends State<_RejectDialog> {
  final TextEditingController _controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('拒绝任务'),
      content: TextField(
        controller: _controller,
        decoration: const InputDecoration(
          hintText: '请输入拒绝理由',
          border: OutlineInputBorder(),
        ),
        maxLines: 3,
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.of(context).pop(),
          child: const Text('取消'),
        ),
        TextButton(
          onPressed: () {
            if (_controller.text.trim().isEmpty) {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('请输入拒绝理由')),
              );
              return;
            }
            Navigator.of(context).pop();
            widget.onConfirm(_controller.text.trim());
          },
          child: const Text('确定'),
        ),
      ],
    );
  }
}